COSC 220 Computer Science II

Pointers and Dynamic Allocation


This lab is intended to give you practice with pointers and dynamic allocation of memory. It should also help your understanding of the relationship between arrays and pointers and with pointers to objects.

TASK 1: Experiments with pointers and dynamic allocation

  1. Download the file Pointers.cpp .
  2. Open Pointers.cpp in an editor and fill in the code following the directions in the file.
  3. Compile Pointers.cpp using g++ -c Pointers.cpp.
  4. Generate the Pointers executable using g++ -o Pointers Pointers.o.
  5. Run the program.

TASK 2: Experiments with pointers and arrays.

  1. Download the following files:
  2. Compile ThreeDimPt.cpp using g++ -c ThreeDimPt.cpp.
  3. Open ClassArr.cpp in an editor and fill in the code following the directions in the file.
  4. Compile ClassArr.cpp using g++ -c ClassArr.cpp.
  5. Generate the ClassArr executable using g++ -o ClassArr ClassArr.o ThreeDimPt.o.
  6. Run the program.

TASK 3: Experiment with array of pointers to objects. This is an array of pointers. The elements stored in the array are pointers. Each pointer in the array points to a ThreeDimPt object.

  1. Copy the following files:
  2. Compile ThreeDimPt.cpp to produce ThreeDimPt.o
  3. Open ClassPtrArr.cpp in vim and fill in the code by following the directions in the file.
  4. Compile ClassPtrArr.cpp to produce ClassPtrArr.o
  5. Link ClassPtrArr.o and ThreeDimPt.o to produce an executable.
  6. Run your executable.

TASK 4: Write a program that prompts for the number of rooms in a house. Use the input n, to declare an array of pointers to rectangle. The elements stored in the array are pointers to rectangle. For each element of this array, it should point to a rectangle object created dynamically. The array should be organized so that the last element is a NULL pointer. In a loop, input the dimensions for the n rooms, then output the total area of the house.   Scan the array to identify the room with the largest perimeter, and output its dimensions. This organization allows you to use the last pointer as a sentinel. You do not need to know how many elements are in the array. You can just loop over the array until the array element is NULL. Thus, functions that take such an array as an argument do not need to also take the size of the array.

  1. Download the following files:
  2. Read the documentation of the auxiliary functions in ex5_36Aux.h. In vim, create a new file named ex5_36Aux.cpp. In this new file, implement the functions specified in ex5_36Aux.h.
  3. Compile d_rect.cpp to produce d_rect.o
  4. Compile ex5_36Aux.cpp to produce ex5_36Aux.o
  5. Compile ex5_36.cpp to produce ex5_36.o
  6. Link ex5_36.o, ex5_36Aux.o, and d_rect.o. to produce an executable.
  7. Run your executable.

WHAT TO SUBMIT TO YOUR INSTRUCTOR:


Updated: 02/09/2021